
<?php
require_once __DIR__ . '/functions.php';

// 检查登录
if (!isLoggedIn()) {
    redirect('index.php', '请先登录', 'warning');
}

$userInfo = getUserInfo();

// 获取筛选条件
$status = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';
$is_signed = $_GET['is_signed'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;  // 减少每页显示数量，提升性能

// 构建查询条件
$where = ['o.user_id = ?'];
$params = [$userInfo['id']];

// 修改状态筛选条件，支持新的结算类型
if ($status) {
    if (in_array($status, ['pending', 'refunded'])) {
        $where[] = 'o.status = ?';
        $params[] = $status;
    } elseif ($status == 'principal') {
        $where[] = 'o.status = ?';
        $params[] = 'settled';
        $where[] = 'o.settlement_type = ?';
        $params[] = 'principal';
    } elseif ($status == 'principal_commission') {
        $where[] = 'o.status = ?';
        $params[] = 'settled';
        $where[] = 'o.settlement_type = ?';
        $params[] = 'principal_commission';
    }
}

if ($search) {
    $where[] = '(o.product_name LIKE ? OR o.tracking_no LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($is_signed !== '') {
    $where[] = 'o.is_signed = ?';
    $params[] = intval($is_signed);
}

$whereClause = implode(' AND ', $where);

// 获取订单总数
$db = getDB();
$stmt = $db->prepare("SELECT COUNT(*) FROM orders o WHERE $whereClause");
$stmt->execute($params);
$total = $stmt->fetchColumn();

// 计算分页
$totalPages = ceil($total / $perPage);
$page = min($page, $totalPages ?: 1);
$offset = ($page - 1) * $perPage;

// 获取订单列表
$stmt = $db->prepare("SELECT o.* FROM orders o 
                     WHERE $whereClause 
                     ORDER BY o.created_at DESC 
                     LIMIT $offset, $perPage");
$stmt->execute($params);
$orders = $stmt->fetchAll();

// 获取公告列表
$announcements = getAnnouncements();

include __DIR__ . '/header.php';
?>

<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <!-- 公告区域 -->
            <?php if (!empty($announcements)): ?>
            <div class="card mb-4 border-warning">
                <div class="card-header bg-warning text-dark">
                    <h5 class="mb-0">
                        <i class="bi bi-megaphone-fill"></i> 系统公告
                    </h5>
                </div>
                <div class="card-body p-0">
                    <div class="announcement-slider" id="announcementSlider">
                        <?php foreach ($announcements as $index => $announcement): ?>
                            <div class="announcement-item p-3 <?php echo $index === 0 ? 'active' : ''; ?>">
                                <div class="d-flex justify-content-between align-items-start mb-3">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-2 text-primary"><?php echo htmlspecialchars($announcement['title']); ?></h6>
                                        <p class="mb-1"><?php echo nl2br(htmlspecialchars($announcement['content'])); ?></p>
                                        <small class="text-muted">
                                            <i class="bi bi-clock"></i> <?php echo date('Y-m-d H:i', strtotime($announcement['created_at'])); ?>
                                        </small>
                                    </div>
                                    <?php if ($announcement['priority'] > 0): ?>
                                        <span class="badge bg-danger ms-2">重要</span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- 公告图片 -->
                                <?php if ($announcement['images']): ?>
                                    <?php 
                                    $images = json_decode($announcement['images'], true);
                                    if (!empty($images)): 
                                    ?>
                                        <div class="announcement-images mt-3">
                                            <h6 class="text-muted mb-2">
                                                <i class="bi bi-images"></i> 相关图片 (<?php echo count($images); ?>张)
                                            </h6>
                                            <div class="row g-2">
                                                <?php foreach ($images as $image): ?>
                                                    <div class="col-6 col-md-4 col-lg-3">
                                                        <div class="announcement-image position-relative">
                                                            <img src="<?php echo htmlspecialchars($image['url']); ?>" 
                                                                 class="img-thumbnail w-100 announcement-img" 
                                                                 style="height: 100px; object-fit: cover; cursor: pointer;"
                                                                 data-src="<?php echo htmlspecialchars($image['url']); ?>"
                                                                 alt="公告图片"
                                                                 title="点击放大">
                                                            <div class="image-overlay position-absolute top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center bg-dark bg-opacity-50 opacity-0 transition-all">
                                                                <i class="bi bi-zoom-in text-white fs-4"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php if (count($announcements) > 1): ?>
                        <div class="card-footer bg-light">
                            <div class="d-flex justify-content-between align-items-center">
                                <button class="btn btn-sm btn-outline-primary" onclick="previousAnnouncement()">
                                    <i class="bi bi-chevron-left"></i> 上一个
                                </button>
                                <div class="announcement-indicators">
                                    <?php foreach ($announcements as $index => $announcement): ?>
                                        <button class="btn btn-sm <?php echo $index === 0 ? 'btn-primary' : 'btn-outline-primary'; ?>" 
                                                onclick="showAnnouncement(<?php echo $index; ?>)" 
                                                style="width: 30px; height: 30px; margin: 0 2px;">
                                            <?php echo $index + 1; ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                                <button class="btn btn-sm btn-outline-primary" onclick="nextAnnouncement()">
                                    下一个 <i class="bi bi-chevron-right"></i>
                                </button>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="bi bi-list-check text-primary"></i> 我的订单
                    <span class="badge bg-secondary"><?php echo $total; ?></span>
                </h2>
                <a href="submit.php" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> 提交新订单
                </a>
            </div>

            <!-- 筛选器 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-4 col-6">
                            <label for="status" class="form-label">订单状态</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">全部状态</option>
                                <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>未结算</option>
                                <option value="principal" <?php echo $status == 'principal' ? 'selected' : ''; ?>>已结本金</option>
                                <option value="principal_commission" <?php echo $status == 'principal_commission' ? 'selected' : ''; ?>>已结本金+佣金</option>
                                <option value="refunded" <?php echo $status == 'refunded' ? 'selected' : ''; ?>>已退还</option>
                            </select>
                        </div>
                        <div class="col-md-4 col-6">
                            <label for="is_signed" class="form-label">签收状态</label>
                            <select class="form-select" id="is_signed" name="is_signed">
                                <option value="">全部</option>
                                <option value="1" <?php echo $is_signed === '1' ? 'selected' : ''; ?>>已签收</option>
                                <option value="0" <?php echo $is_signed === '0' ? 'selected' : ''; ?>>未签收</option>
                            </select>
                        </div>
                        <div class="col-md-6 col-12">
                            <label for="search" class="form-label">搜索订单</label>
                            <input type="text" class="form-control" id="search" name="search" 
                                   placeholder="商品名称、物流单号" 
                                   value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-md-2 col-12 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2 flex-fill">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <a href="orders.php" class="btn btn-secondary flex-fill">
                                <i class="bi bi-arrow-counterclockwise"></i> 重置
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="row mb-4">
                <div class="col-6 col-md-3 mb-3">
                    <div class="card bg-warning text-white">
                        <div class="card-body text-center p-2">
                            <h6 class="card-title mb-1">
                                <i class="bi bi-clock-history"></i> 未结算
                            </h6>
                            <?php
                            $stmt = $db->prepare("SELECT COUNT(*) FROM orders WHERE user_id = ? AND status = 'pending'");
                            $stmt->execute([$userInfo['id']]);
                            $pendingCount = $stmt->fetchColumn();
                            ?>
                            <h4 class="mb-0"><?php echo $pendingCount; ?></h4>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-md-3 mb-3">
                    <div class="card bg-info text-white">
                        <div class="card-body text-center p-2">
                            <h6 class="card-title mb-1">
                                <i class="bi bi-currency-dollar"></i> 已结本金
                            </h6>
                            <?php
                            $stmt = $db->prepare("SELECT COUNT(*) FROM orders WHERE user_id = ? AND status = 'settled' AND settlement_type = 'principal'");
                            $stmt->execute([$userInfo['id']]);
                            $principalCount = $stmt->fetchColumn();
                            ?>
                            <h4 class="mb-0"><?php echo $principalCount; ?></h4>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-md-3 mb-3">
                    <div class="card bg-success text-white">
                        <div class="card-body text-center p-2">
                            <h6 class="card-title mb-1">
                                <i class="bi bi-cash-stack"></i> 已结本金+佣金
                            </h6>
                            <?php
                            $stmt = $db->prepare("SELECT COUNT(*) FROM orders WHERE user_id = ? AND status = 'settled' AND settlement_type = 'principal_commission'");
                            $stmt->execute([$userInfo['id']]);
                            $commissionCount = $stmt->fetchColumn();
                            ?>
                            <h4 class="mb-0"><?php echo $commissionCount; ?></h4>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-md-3 mb-3">
                    <div class="card bg-danger text-white">
                        <div class="card-body text-center p-2">
                            <h6 class="card-title mb-1">
                                <i class="bi bi-arrow-return-left"></i> 已退还
                            </h6>
                            <?php
                            $stmt = $db->prepare("SELECT COUNT(*) FROM orders WHERE user_id = ? AND status = 'refunded'");
                            $stmt->execute([$userInfo['id']]);
                            $refundedCount = $stmt->fetchColumn();
                            ?>
                            <h4 class="mb-0"><?php echo $refundedCount; ?></h4>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 桌面端表格视图 -->
            <div class="card d-none d-md-block">
                <div class="card-body">
                    <?php if (empty($orders)): ?>
                        <div class="text-center py-5">
                            <i class="bi bi-inbox display-1 text-muted"></i>
                            <h4 class="mt-3 text-muted">暂无订单</h4>
                            <p class="text-muted">您还没有提交任何订单</p>
                            <a href="submit.php" class="btn btn-primary mt-3">
                                <i class="bi bi-plus-circle"></i> 提交第一个订单
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>商品名称</th>
                                        <th>收货地</th>
                                        <th>下单平台</th>
                                        <th>物流单号</th>
                                        <th>金额</th>
                                        <th>付款方式</th>
                                        <th>状态</th>
                                        <th>签收</th>
                                        <th>提交时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($orders as $order): ?>
                                        <tr>
                                            <td><?php echo $order['id']; ?></td>
                                            <td>
                                                <span class="text-truncate d-inline-block" style="max-width: 150px;" title="<?php echo htmlspecialchars($order['product_name']); ?>">
                                                    <?php echo htmlspecialchars($order['product_name']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars(getConfigOptionLabel('delivery_location', $order['delivery_location'])); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars(getConfigOptionLabel('order_platform', $order['order_platform'])); ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($order['tracking_no']); ?></td>
                                            <td><?php echo formatAmount($order['order_amount']); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $order['payment_method'] == 'group_paid' ? 'warning' : 'info'; ?>">
                                                    <?php echo getPaymentMethodText($order['payment_method']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($order['status'] == 'pending'): ?>
                                                    <span class="badge bg-warning">未结算</span>
                                                <?php elseif ($order['status'] == 'settled'): ?>
                                                    <?php if ($order['settlement_type'] == 'principal'): ?>
                                                        <span class="badge bg-info">已结本金</span>
                                                    <?php elseif ($order['settlement_type'] == 'principal_commission'): ?>
                                                        <span class="badge bg-success">已结本金+佣金</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-success">已结算</span>
                                                    <?php endif; ?>
                                                <?php elseif ($order['status'] == 'refunded'): ?>
                                                    <span class="badge bg-danger">已退还</span>
                                                <?php endif; ?>
                                                
                                                <?php if ($order['status'] == 'settled' && $order['settlement_amount']): ?>
                                                    <br>
                                                    <small class="text-success">
                                                        结算: <?php echo formatAmount($order['settlement_amount']); ?>
                                                    </small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo getOrderSignClass($order['is_signed']); ?>">
                                                    <?php echo getOrderSignText($order['is_signed']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo formatTime($order['created_at']); ?></td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                                            onclick="showOrderDetails(<?php echo $order['id']; ?>)"
                                                            data-bs-toggle="tooltip" title="查看详情">
                                                        <i class="bi bi-eye"></i>
                                                    </button>
                                                    
                                                    <?php if ($order['settlement_type'] != 'principal_commission'): ?>
                                                        <a href="edit_order.php?id=<?php echo $order['id']; ?>" 
                                                           class="btn btn-sm btn-outline-warning" 
                                                           data-bs-toggle="tooltip" title="修改订单">
                                                            <i class="bi bi-pencil"></i>
                                                        </a>
                                                        
                                                    <?php endif; ?>
                                                    <?php if ($order['settlement_type'] != 'principal_commission' && $order['settlement_type'] != 'principal'): ?>
                                                        <button type="button" class="btn btn-sm btn-outline-danger" 
                                                                onclick="deleteOrder(<?php echo $order['id']; ?>, '<?php echo htmlspecialchars($order['product_name']); ?>')"
                                                                data-bs-toggle="tooltip" title="删除订单">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    
                                                    <?php if ($order['order_screenshot']): ?>
                                                        <a href="<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>" 
                                                           target="_blank" class="btn btn-sm btn-outline-info" 
                                                           data-bs-toggle="tooltip" title="订单截图">
                                                            <i class="bi bi-image"></i>
                                                        </a>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <?php if ($totalPages > 1): ?>
                            <nav aria-label="订单分页" class="mt-4">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&is_signed=<?php echo urlencode($is_signed); ?>">
                                            <i class="bi bi-chevron-left"></i> 上一页
                                        </a>
                                    </li>
                                    
                                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                        <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&is_signed=<?php echo urlencode($is_signed); ?>">
                                                    <?php echo $i; ?>
                                                </a>
                                            </li>
                                        <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                    <?php endfor; ?>
                                    
                                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&is_signed=<?php echo urlencode($is_signed); ?>">
                                            下一页 <i class="bi bi-chevron-right"></i>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- 移动端卡片视图 -->
            <div class="d-md-none">
                <div class="row g-3" id="mobileOrdersList">
                    <?php if (empty($orders)): ?>
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body text-center py-5">
                                    <i class="bi bi-inbox display-1 text-muted"></i>
                                    <h4 class="mt-3 text-muted">暂无订单</h4>
                                    <p class="text-muted">您还没有提交任何订单</p>
                                    <a href="submit.php" class="btn btn-primary mt-3">
                                        <i class="bi bi-plus-circle"></i> 提交第一个订单
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <?php foreach ($orders as $order): ?>
                            <div class="col-12">
                                <div class="card order-card <?php echo $order['status']; ?>">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="card-title mb-0 text-truncate" style="max-width: 70%;">
                                                <?php echo htmlspecialchars($order['product_name']); ?>
                                            </h6>
                                            <?php if ($order['status'] == 'pending'): ?>
                                                <span class="badge bg-warning">未结算</span>
                                            <?php elseif ($order['status'] == 'settled'): ?>
                                                <?php if ($order['settlement_type'] == 'principal'): ?>
                                                    <span class="badge bg-info">已结本金</span>
                                                <?php elseif ($order['settlement_type'] == 'principal_commission'): ?>
                                                    <span class="badge bg-success">已结本金+佣金</span>
                                                <?php else: ?>
                                                    <span class="badge bg-success">已结算</span>
                                                <?php endif; ?>
                                            <?php elseif ($order['status'] == 'refunded'): ?>
                                                <span class="badge bg-danger">已退还</span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="order-info">
                                            <div class="row small text-muted g-1">
                                                <div class="col-6">
                                                    <i class="bi bi-truck"></i> <?php echo htmlspecialchars($order['tracking_no']); ?>
                                                </div>
                                                <div class="col-6 text-end">
                                                    <i class="bi bi-currency-yen"></i> <?php echo formatAmount($order['order_amount']); ?>
                                                </div>
                                                <div class="col-6">
                                                    <i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars(getConfigOptionLabel('delivery_location', $order['delivery_location'])); ?>
                                                </div>
                                                <div class="col-6 text-end">
                                                    <i class="bi bi-<?php echo $order['is_signed'] ? 'check-circle text-success' : 'clock text-warning'; ?>"></i>
                                                    <?php echo getOrderSignText($order['is_signed']); ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="order-actions mt-2 pt-2 border-top">
                                            <div class="btn-group w-100" role="group">
                                                <button type="button" class="btn btn-sm btn-outline-primary" 
                                                        onclick="showOrderDetails(<?php echo $order['id']; ?>)">
                                                    <i class="bi bi-eye"></i> 详情
                                                </button>
                                                <?php if ($order['settlement_type'] != 'principal_commission'): ?>
                                                    <a href="edit_order.php?id=<?php echo $order['id']; ?>" 
                                                       class="btn btn-sm btn-outline-warning">
                                                        <i class="bi bi-pencil"></i> 修改
                                                    </a>
                                                <?php endif; ?>
                                                <?php if ($order['order_screenshot']): ?>
                                                    <a href="<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>" 
                                                       target="_blank" class="btn btn-sm btn-outline-info">
                                                        <i class="bi bi-image"></i> 截图
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        
                        <!-- 移动端分页 -->
                        <?php if ($totalPages > 1): ?>
                            <div class="col-12">
                                <nav aria-label="订单分页" class="mt-4">
                                    <ul class="pagination justify-content-center">
                                        <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&is_signed=<?php echo urlencode($is_signed); ?>">
                                                <i class="bi bi-chevron-left"></i> 上一页
                                            </a>
                                        </li>
                                        
                                        <li class="page-item disabled">
                                            <span class="page-link"><?php echo $page; ?>/<?php echo $totalPages; ?></span>
                                        </li>
                                        
                                        <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&is_signed=<?php echo urlencode($is_signed); ?>">
                                                下一页 <i class="bi bi-chevron-right"></i>
                                            </a>
                                        </li>
                                    </ul>
                                </nav>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 订单详情模态框 -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">订单详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="orderDetailsContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>

<style>
/* 移动端优化样式 */
@media (max-width: 767.98px) {
    .table-responsive {
        display: none;
    }
    
    .order-card {
        margin-bottom: 1rem;
        border-radius: 10px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        transition: all 0.2s ease;
        will-change: transform;
        contain: layout style paint;
    }
    
    .order-card:active {
        transform: scale(0.98);
    }
    
    .order-info .row {
        font-size: 0.8rem;
    }
    
    .order-actions .btn-group .btn {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
    }
    
    /* 优化筛选表单 */
    .card-body .row.g-3 {
        margin-bottom: 0;
    }
    
    .card-body .col-md-4,
    .card-body .col-md-6,
    .card-body .col-md-2 {
        margin-bottom: 1rem;
    }
    
    /* 优化统计卡片 */
    .row.mb-4 .col-md-3 {
        margin-bottom: 1rem;
    }
    
    /* 优化公告 */
    .announcement-images .row .col-6 {
        flex: 0 0 50%;
        max-width: 50%;
    }
    
    /* 减少移动端动画复杂度 */
    .card:hover {
        transform: none;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
    .btn:hover {
        transform: none;
    }
}

/* 桌面端保持表格显示 */
@media (min-width: 768px) {
    #mobileOrdersList {
        display: none;
    }
}

/* 公告图片样式增强 */
.announcement-slider {
    position: relative;
    overflow: hidden;
}

.announcement-item {
    display: none;
    transition: all 0.3s ease;
}

.announcement-item.active {
    display: block;
}

.announcement-indicators button {
    transition: all 0.3s ease;
}

.text-truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 公告图片样式增强 */
.announcement-image {
    transition: all 0.3s ease;
    border-radius: 8px;
    overflow: hidden;
    position: relative;
}

.announcement-image:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.announcement-image .image-overlay {
    transition: all 0.3s ease;
    cursor: pointer;
}

.announcement-image:hover .image-overlay {
    opacity: 1 !important;
    background: rgba(0,0,0,0.7);
}

.announcement-img {
    transition: transform 0.3s ease;
}

.announcement-image:hover .announcement-img {
    transform: scale(1.05);
}

/* 图片查看器模态框样式优化 */
#announcementImageViewer .modal-content {
    background: transparent;
    box-shadow: none;
    border: none;
}

#announcementImageViewer .modal-header {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1055;
    border: none;
    padding: 0.5rem;
}

#announcementImageViewer .btn-close {
    filter: invert(1);
    opacity: 0.8;
    background-size: 1.2em;
    padding: 0.5em;
}

#announcementImageViewer .btn-close:hover {
    opacity: 1;
    transform: scale(1.1);
}

#announcementImageViewer .modal-body {
    padding: 2rem;
    background: rgba(0,0,0,0.8);
    backdrop-filter: blur(10px);
}

#announcementImageViewer .modal-body img {
    box-shadow: 0 20px 60px rgba(0,0,0,0.5);
    border: 2px solid rgba(255,255,255,0.1);
}

/* 确保过渡效果正常工作 */
.transition-all {
    transition: all 0.3s ease;
}

/* 图片悬停效果 */
.announcement-image {
    cursor: pointer;
}

.announcement-image .image-overlay {
    pointer-events: none; /* 允许点击穿透到图片 */
}

/* 确保图片容器有相对定位 */
.announcement-image {
    position: relative;
}

/* 图片查看器改进样式 */
#announcementImageViewer .modal-content {
    background: rgba(0, 0, 0, 0.9) !important;
    border-radius: 12px;
}

#announcementImageViewer .modal-body {
    padding: 2rem;
}

#announcementImageViewer .modal-footer {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    border-radius: 8px;
    margin-bottom: 20px;
}
</style>

<script>
// 公告轮播功能
let currentAnnouncement = 0;
const announcements = document.querySelectorAll('.announcement-item');
const indicators = document.querySelectorAll('.announcement-indicators button');

function showAnnouncement(index) {
    // 隐藏当前公告
    announcements[currentAnnouncement].classList.remove('active');
    indicators[currentAnnouncement].classList.remove('btn-primary');
    indicators[currentAnnouncement].classList.add('btn-outline-primary');
    
    // 显示目标公告
    currentAnnouncement = index;
    announcements[currentAnnouncement].classList.add('active');
    indicators[currentAnnouncement].classList.remove('btn-outline-primary');
    indicators[currentAnnouncement].classList.add('btn-primary');
    
    // 触发自定义事件
    const event = new CustomEvent('announcementChanged');
    document.getElementById('announcementSlider').dispatchEvent(event);
}

function nextAnnouncement() {
    const nextIndex = (currentAnnouncement + 1) % announcements.length;
    showAnnouncement(nextIndex);
}

function previousAnnouncement() {
    const prevIndex = (currentAnnouncement - 1 + announcements.length) % announcements.length;
    showAnnouncement(prevIndex);
}

// 自动轮播公告
if (announcements.length > 1) {
    setInterval(nextAnnouncement, 5000);
}

function showOrderDetails(orderId) {
    // 显示加载状态
    document.getElementById('orderDetailsContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('orderDetailsModal'));
    modal.show();
    
    // 加载订单详情
    fetch('api/order_details.php?id=' + orderId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const order = data.data;
                
                // 更新状态显示逻辑
                let statusText, statusClass;
                if (order.status === 'pending') {
                    statusText = '未结算';
                    statusClass = 'warning';
                } else if (order.status === 'settled') {
                    if (order.settlement_type === 'principal') {
                        statusText = '已结本金';
                        statusClass = 'info';
                    } else if (order.settlement_type === 'principal_commission') {
                        statusText = '已结本金+佣金';
                        statusClass = 'success';
                    } else {
                        statusText = '已结算';
                        statusClass = 'success';
                    }
                } else if (order.status === 'refunded') {
                    statusText = '已退还';
                    statusClass = 'danger';
                }
                
                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>订单ID：</strong></td><td>${order.id}</td></tr>
                                <tr><td><strong>商品名称：</strong></td><td>${order.product_name}</td></tr>
                                <tr><td><strong>收货地：</strong></td><td>${order.delivery_location_label}</td></tr>
                                <tr><td><strong>下单平台：</strong></td><td>${order.order_platform_label}</td></tr>
                                <tr><td><strong>物流单号：</strong></td><td>${order.tracking_no}</td></tr>
                                <tr><td><strong>下单金额：</strong></td><td>¥${parseFloat(order.order_amount).toFixed(2)}</td></tr>
                                <tr><td><strong>付款方式：</strong></td><td>${order.payment_method_label}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>订单状态：</strong></td><td>
                                    <span class="badge bg-${statusClass}">${statusText}</span>
                                </td></tr>
                                <tr><td><strong>签收状态：</strong></td><td>
                                    <span class="badge bg-${order.is_signed ? 'success' : 'warning'}">
                                        ${order.is_signed ? '已签收' : '未签收'}
                                    </span>
                                </td></tr>
                                <tr><td><strong>取件码：</strong></td><td>
                                    ${order.pickup_code ? `<span class="badge bg-info">${order.pickup_code}</span>` : '<span class="text-muted">无</span>'}
                                </td></tr>
                                <tr><td><strong>结算类型：</strong></td><td>${order.settlement_type_label || '未结算'}</td></tr>
                                <tr><td><strong>提交时间：</strong></td><td>${new Date(order.created_at).toLocaleString('zh-CN')}</td></tr>
                `;
                
                if (order.status === 'settled' && order.settlement_amount) {
                    html += `<tr><td><strong>结算金额：</strong></td><td class="text-success">¥${parseFloat(order.settlement_amount).toFixed(2)}</td></tr>`;
                }
                
                if (order.notes) {
                    html += `<tr><td><strong>备注信息：</strong></td><td>${order.notes.replace(/\n/g, '<br>')}</td></tr>`;
                }
                
                if (order.settlement_info) {
                    html += `<tr><td><strong>结算信息：</strong></td><td><span class="text-danger">${order.settlement_info.replace(/\n/g, '<br>')}</span></td></tr>`;
                }
                
                html += `
                            </table>
                        </div>
                    </div>
                `;
                
                if (order.order_screenshot) {
                    html += `
                        <div class="mt-4">
                            <h6>订单截图</h6>
                            <img src="${order.screenshot_url}" class="img-fluid rounded border" style="max-height: 300px;">
                        </div>
                    `;
                }
                
                if (order.settlement_screenshot) {
                    html += `
                        <div class="mt-4">
                            <h6>结算截图</h6>
                            <img src="${order.settlement_screenshot_url}" class="img-fluid rounded border" style="max-height: 300px;">
                        </div>
                    `;
                }
                
                document.getElementById('orderDetailsContent').innerHTML = html;
            } else {
                document.getElementById('orderDetailsContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('orderDetailsContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

function deleteOrder(orderId, productName) {
    if (confirm(`确定要删除订单 "${productName}" 吗？此操作不可撤销！`)) {
        // 显示加载状态
        const originalText = event.target.innerHTML;
        event.target.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span>';
        event.target.disabled = true;
        
        fetch('api/order_delete.php?id=' + orderId, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('订单删除成功', 'success');
                // 延迟刷新页面，让用户看到提示消息
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                showToast(data.message || '删除失败', 'error');
                // 恢复按钮状态
                event.target.innerHTML = originalText;
                event.target.disabled = false;
            }
        })
        .catch(error => {
            showToast('删除失败：' + error.message, 'error');
            // 恢复按钮状态
                event.target.innerHTML = originalText;
                event.target.disabled = false;
        });
    }
}

// 公告图片点击放大功能
function initAnnouncementImageClick() {
    // 使用事件委托来处理动态加载的图片
    document.addEventListener('click', function(event) {
        // 检查点击的是否是公告图片
        if (event.target.classList.contains('announcement-img')) {
            const imageUrl = event.target.getAttribute('data-src') || event.target.src;
            viewAnnouncementImage(imageUrl);
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
        
        // 检查点击的是否是图片放大图标
        if (event.target.classList.contains('bi-zoom-in') || 
            event.target.closest('.image-overlay')) {
            const img = event.target.closest('.announcement-image').querySelector('.announcement-img');
            const imageUrl = img.getAttribute('data-src') || img.src;
            viewAnnouncementImage(imageUrl);
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
    });
}

// 查看公告图片
function viewAnnouncementImage(url) {
    // 创建图片查看器模态框
    const modalHtml = `
        <div class="modal fade" id="announcementImageViewer" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-centered">
                <div class="modal-content bg-transparent border-0">
                    <div class="modal-header border-0 position-absolute top-0 end-0 z-3">
                        <button type="button" class="btn-close btn-close-white bg-dark bg-opacity-50 rounded-circle p-2" 
                                data-bs-dismiss="modal" aria-label="Close" style="margin: 10px;"></button>
                    </div>
                    <div class="modal-body text-center p-0 d-flex align-items-center justify-content-center">
                        <img src="${url}" class="img-fluid rounded shadow-lg" 
                             style="max-height: 85vh; max-width: 90vw; object-fit: contain; cursor: zoom-out;"
                             onclick="closeImageViewer()">
                    </div>
                    <div class="modal-footer border-0 position-absolute bottom-0 start-50 translate-middle-x">
                        <a href="${url}" target="_blank" class="btn btn-sm btn-light">
                            <i class="bi bi-box-arrow-up-right"></i> 在新标签页打开
                        </a>
                        <button class="btn btn-sm btn-light" onclick="downloadImage('${url}')">
                            <i class="bi bi-download"></i> 下载图片
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 移除已存在的模态框
    const existingModal = document.getElementById('announcementImageViewer');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 添加新模态框到页面
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 显示模态框
    const modalElement = document.getElementById('announcementImageViewer');
    const modal = new bootstrap.Modal(modalElement);
    
    // 点击模态框背景关闭
    modalElement.addEventListener('click', function(e) {
        if (e.target === this) {
            modal.hide();
        }
    });
    
    // 键盘事件支持
    document.addEventListener('keydown', function handleKeydown(e) {
        if (e.key === 'Escape') {
            modal.hide();
        }
    });
    
    modal.show();
    
    // 模态框关闭后清理
    modalElement.addEventListener('hidden.bs.modal', function() {
        document.removeEventListener('keydown', handleKeydown);
        this.remove();
    });
}

// 关闭图片查看器
function closeImageViewer() {
    const modal = bootstrap.Modal.getInstance(document.getElementById('announcementImageViewer'));
    if (modal) {
        modal.hide();
    }
}

// 下载图片
function downloadImage(url) {
    const link = document.createElement('a');
    link.href = url;
    link.download = 'announcement_' + Date.now() + '.jpg';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 初始化悬停效果
function initAnnouncementImageHover() {
    const announcementImageContainers = document.querySelectorAll('.announcement-image');
    announcementImageContainers.forEach(container => {
        container.addEventListener('mouseenter', function() {
            const overlay = this.querySelector('.image-overlay');
            if (overlay) {
                overlay.classList.remove('opacity-0');
            }
        });
        
        container.addEventListener('mouseleave', function() {
            const overlay = this.querySelector('.image-overlay');
            if (overlay) {
                overlay.classList.add('opacity-0');
            }
        });
    });
}

// 移动端触摸优化
let touchStartY = 0;
let touchEndY = 0;

document.addEventListener('touchstart', function(e) {
    touchStartY = e.changedTouches[0].screenY;
}, { passive: true });

document.addEventListener('touchend', function(e) {
    touchEndY = e.changedTouches[0].screenY;
    handleSwipe();
}, { passive: true });

function handleSwipe() {
    // 可以添加滑动刷新或加载更多的逻辑
}

// 图片懒加载
function initLazyLoad() {
    const lazyImages = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
                imageObserver.unobserve(img);
            }
        });
    });
    
    lazyImages.forEach(img => imageObserver.observe(img));
}

// 在页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initAnnouncementImageClick();
    initAnnouncementImageHover();
    initLazyLoad();
    
    // 移动端优化：减少重绘
    const mobileOrders = document.getElementById('mobileOrdersList');
    if (mobileOrders) {
        mobileOrders.style.willChange = 'transform';
    }
    
    // 如果公告轮播切换，重新初始化悬停效果
    const announcementSlider = document.getElementById('announcementSlider');
    if (announcementSlider) {
        // 监听自定义的公告切换事件
        announcementSlider.addEventListener('announcementChanged', function() {
            setTimeout(initAnnouncementImageHover, 100);
        });
    }
});

// 初始化工具提示
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>
